package fun.linze.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import fun.linze.domain.TUser;
import fun.linze.dto.UserRegisterDto;
import fun.linze.mapper.TUserMapper;
import fun.linze.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
* @author wangy
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2025-06-21 10:30:00
*/
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser>
    implements TUserService, UserDetailsService {

    private final TUserMapper tUserMapper;

    @Autowired
    public TUserServiceImpl(TUserMapper tUserMapper) {
        this.tUserMapper = tUserMapper;
    }

    @Override
    public void registerUser(UserRegisterDto userRegisterDto) {
        // 检查用户名是否已存在
        if (this.getOne(new QueryWrapper<TUser>().eq("username", userRegisterDto.getUsername())) != null) {
            throw new IllegalStateException("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (this.getOne(new QueryWrapper<TUser>().eq("email", userRegisterDto.getEmail())) != null) {
            throw new IllegalStateException("邮箱已存在");
        }

        TUser user = new TUser();
        user.setUsername(userRegisterDto.getUsername());
        user.setPassword(userRegisterDto.getPassword());
        user.setNickname(userRegisterDto.getNickname());
        user.setEmail(userRegisterDto.getEmail());
        this.save(user);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser tUser = tUserMapper.selectOne(new QueryWrapper<TUser>().eq("username", username));
        if (tUser == null) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }
        return new User(tUser.getUsername(), tUser.getPassword(), new ArrayList<>());
    }
}
